﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Web.Wap.Code;
using ZLCMS.Business.WeixinService;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.AdvancedAPIs;
using DotNet.Common.Command;
using ZLCMS.Commands.Member.Commands.Member;
using DotNet.Common.NHibernateUtil;

namespace ZLCMS.Web.Wap.Member
{
    public partial class BindWeixin : MemberPageBase
    {
        protected string ResultMessage { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            //包含openid信息
            if (!string.IsNullOrEmpty(Request["openid"]) || !string.IsNullOrEmpty(Request["code"]))
            {
                ICommandResult<LoginOAuthResult> result = new LoginWeixinCommand().Execute(new LoginOAuthParameter() { Context = this.Context });
                if (!string.IsNullOrEmpty(result.Result.Token))
                {
                    ResultMessage = "当前微信已被绑定，不能重复绑定";
                }
                else if (!string.IsNullOrEmpty(result.Result.OAuthResult.OpenId))
                {
                    using (NHibernate.ISession session = SessionFactoryHelper.CreateSession())
                    {
                        session.CreateSQLQuery(@"update member_info set wx_open_id=:openid,sex=ifnull(sex,:sex),member_name=ifnull(member_name,:name)
                ,nick_name=ifnull(nick_name,:name),photo_url=ifnull(photo_url,:photo) where account_id=:acc")
                        .SetParameter("acc", CurrentMemberAccount)
                        .SetParameter("openid", result.Result.OAuthResult.OpenId)
                        .SetParameter("sex", result.Result.OAuthResult.Sex)
                        .SetParameter("name", result.Result.OAuthResult.NickName)
                        .SetParameter("photo", result.Result.OAuthResult.PhotoUrl)
                        .ExecuteUpdate();
                    }

                    ResultMessage = "绑定成功";
                }
            }
            //可用网页授权
            else if (WeixinUtil.GetConfig("admin").OauthEnable == "1")
            {
                string url = OAuth.GetAuthorizeUrl(WeixinUtil.GetAppid("admin"), ServerUtil.GetRootURI() + Context.Request.RawUrl, "myself", OAuthScope.snsapi_userinfo);
                Response.Redirect(url);
            }
            else
            {
                ResultMessage = "参数错误";
            }
        }
    }
}